package com.shoppingmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.shoppingmall.common.ServletResponse;
import com.shoppingmall.dao.ShippingMapper;
import com.shoppingmall.pojo.Shipping;
import com.shoppingmall.service.ShippingService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by
 *
 * @author touni
 * @date 2019/3/22
 * @time 10:38
 */
@Service
public class ShippingServiceImpl implements ShippingService {
    @Autowired
    private ShippingMapper shippingMapper;


    @Override
    public ServletResponse addOrUpdateShippingAddress(Shipping shipping) {
        //根据是否有shipping中的id来判断是增加还是修改
        if (null != shipping.getId()){
            //update
            int flag = shippingMapper.updateByPrimaryKey(shipping);
            if (1 != flag){
                return ServletResponse.createByErrorMessage("修改失败！！");
            }
            return ServletResponse.createBySuccess("修改成功！！");
        }
        //insert
        int flag = shippingMapper.insert(shipping);
        if (1 != flag){
            return ServletResponse.createByErrorMessage("添加失败！！");
        }
        return ServletResponse.createBySuccess("添加成功！！");
    }

    @Override
    public ServletResponse deleteShippingAddress(Integer userId, Integer shippingId) {
        int flag = shippingMapper.deleteByUserIdAndShippingId(userId, shippingId);
        if (1 != flag){
            return ServletResponse.createByErrorMessage("删除失败");
        }


        return ServletResponse.createBySuccess("删除成功！！！");
    }



    @Override
    public ServletResponse selectShippingAddress(Integer userId, Integer shippingId) {
        Shipping shippingFromUserIdAndShippingId = shippingMapper.selectByUserIdAndShippingId(userId,shippingId);
        if (null == shippingFromUserIdAndShippingId){
            return ServletResponse.createByErrorMessage("无法查询到，请重试");
        }
        return ServletResponse.createBySuccess(shippingFromUserIdAndShippingId);
    }



    @Override
    public ServletResponse listShippingAddress(Integer userId, Integer pageNum, Integer pageSize) {
        //设置分页
        PageHelper.startPage(pageNum,pageSize);
        //执行查询逻辑
        List<Shipping> shippingList = shippingMapper.selectByUserId(userId);

        if (CollectionUtils.isEmpty(shippingList)){
            return ServletResponse.createByErrorMessage("该用户未添加过地址信息，请开始添加");
        }
        return ServletResponse.createBySuccess(shippingList);
    }
}
